package com.bawei.login.vm

import androidx.lifecycle.viewModelScope
import com.bawei.common.vm.BaseViewModel
import com.bawei.login.intent.AccountViewIntent
import com.bawei.login.model.AccountRepository
import com.bawei.login.state.AccountUiState
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import javax.inject.Inject

/**
 * Author: Jason Zhang
 * Date: 2025/2/13
 * Desc:
 */
@HiltViewModel
class AccountViewModel @Inject constructor(private val repository: AccountRepository):BaseViewModel<AccountViewIntent>() {

    private val _uiState = MutableStateFlow<AccountUiState>(AccountUiState.EmptyState)
    val uiState: StateFlow<AccountUiState> = _uiState.asStateFlow()

    override fun dispatchIntent(intent: AccountViewIntent) {
       when(intent){
           is AccountViewIntent.LoginToServer -> loginToServer(intent.userName, intent.password)
           is AccountViewIntent.RegisterToServer -> registerToServer(intent.userName, intent.password)
       }
    }

    private fun loginToServer(userName: String, password: String) {
        viewModelScope.launch(Dispatchers.IO) {
            try {
                val (code, data, msg) = repository.loginToServer(userName, password)
                withContext(Dispatchers.Main){
                    if (code == 0){
                        _uiState.value = AccountUiState.LoginToServerSuccess(data)
                    }else{
                        _uiState.value = AccountUiState.LoginToServerFail(msg)
                    }
                }
            }catch (e:Exception){
                e.printStackTrace()
                withContext(Dispatchers.Main){
                    _uiState.value = AccountUiState.LoginToServerFail("登录接口异常")
                }
            }finally {
                cancel()
            }
        }
    }



    private fun registerToServer(userName: String, password: String) {
        viewModelScope.launch(Dispatchers.IO) {
            try {
                val (code, data, msg) = repository.registerToServer(userName, password)
                withContext(Dispatchers.Main){
                    if (code == 0){
                        _uiState.value = AccountUiState.RegisterToServerSuccess(data)
                    }else{
                        _uiState.value = AccountUiState.RegisterToServerFail(msg)
                    }
                }
            }catch (e:Exception){
                e.printStackTrace()
                withContext(Dispatchers.Main){
                    _uiState.value = AccountUiState.RegisterToServerFail("注册接口异常")
                }
            }finally {
                cancel()
            }
        }

    }





}